<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="渠道" prop="channel_ids">
        <el-select
          v-model="queryParams.channel_ids"
          placeholder="请选择渠道"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="channel in channelList"
            :key="channel.id"
            :label="channel.channel_name"
            :value="channel.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="sort_type">
        <el-select v-model="queryParams.sort_type" clearable placeholder="类型">
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- v-hasPermi="['api:v1:addChannelGroup']" -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['api:czChannelGroup:addGroup']"
          >新增渠道组</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['api:v1:delChannelGroup']" -->
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['api:czChannelGroup:delGroup']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="title" />
      <el-table-column label="渠道" align="center" prop="channels" />
      <el-table-column prop="sort_type" label="类型" align="center">
        <template #default="scope">
          <span>{{ scope.row.sort_type === 1 ? "人工排序" : "价格排序" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="created_at"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.created_time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- v-hasPermi="['api:v1:updateChannelGroup']" -->
          <el-button
            size="small"
            type="primary"
            link
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['api:czChannelGroup:getGroup']"
            >修改</el-button
          >
          <!-- v-hasPermi="['api:v1:delChannelGroup']" -->
          <el-button
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:czChannelGroup:delGroup']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      v-model="open"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="排序类型" prop="sort_type">
          <el-select
            v-model="form.sort_type"
            clearable
            placeholder="请选择排序类型"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道">
          <el-table
            border
            max-height="500"
            :data="channelList"
            ref="tableDate"
            @selection-change="handleSelectionChange2"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              prop="channel_name"
              label="渠道名称"
              align="center"
            />
            <el-table-column prop="sort" label="排序" align="center">
              <template #default="scope">
                <el-input
                  :min="1"
                  v-model="scope.row.sort"
                  placeholder="请输入排序"
                  clearable
                  width="100"
                  size="small"
                  autocomplete="off"
                />
              </template>
            </el-table-column>
            <el-table-column prop="submit_nums" label="重提次数" align="center">
              <template #default="scope">
                <el-input
                  :min="1"
                  v-model="scope.row.submit_nums"
                  placeholder="请输入重提次数"
                  clearable
                  width="100"
                  size="small"
                  autocomplete="off"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChannelGroup,
  delChannelGroup,
  addChannelGroup,
  getChannelGroup,
} from "@/api/channel/channelGroup";
// listAllChannel
import { getAllList as listAllChannel } from "@/api/channel";
// import { isNumberStr } from "@/utils/index";
// import { addCustomer } from "@/api/cz/customer";

export default {
  name: "rechargechannelgroup",
  data() {
    return {
      tableDate: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      check_ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      channelList: [],
      open: false,
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      single2: true,
      multipleSelection2: [],
      ids2: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        title: undefined,
        sort_type: undefined,
        channel_ids: undefined,
      },
      // 表单参数
      form: {},
      rules: {
        title: [{ required: true, message: "请输入名称", trigger: "blur" }],
        sort_type: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
      },
      typeList: [
        { id: 1, name: "人工排序" },
        { id: 2, name: "价格排序" },
      ],
    };
  },
  created() {
    this.getChannelList();
    this.getList();
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      params.pageNum = params.page;
      listChannelGroup(this.addDateRange(params, this.dateRange)).then(
        (response) => {
          // console.log("response", response);
          this.dataList = response.data.items;
          this.dataList.forEach((ele, index) => {
            let items = ele.items.map((item) => {
              return item.channel.channel_name;
            });
            this.dataList[index].channels = items.join("，");
          });
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    getChannelList() {
      listAllChannel().then((response) => {
        response.data.forEach((item) => {
          item.sort = 1;
          item.submit_nums = 1;
          // this.$set(item, "sort", 1);
          // this.$set(item, "submit_nums", 1);
        });
        this.channelList = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加渠道组";
      // this.$router.push({ path: "addGroup" });
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getChannelGroup(id).then((response) => {
        console.log(response);
        this.form = response.data.data;
        this.check_ids = response.data.check_ids;
        this.open = true;
        this.channelList.forEach((channel) => {
          if (this.check_ids?.indexOf(channel.id) > -1) {
            this.$nextTick(() => {
              this.$refs.tableDate?.toggleRowSelection(channel);
            });
          }
        });

        this.title = "修改渠道组";
      });
      // this.$router.push({ path: "addGroup?id=" + row.id });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multipleSelection = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = [row.id] || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + dictIds + '"的数据项？')
        .then(function () {
          return delChannelGroup(dictIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleSelectionChange2(selection) {
      this.multipleSelection2 = selection;
      this.ids2 = selection.map((item) => item.id);
      this.single2 = selection.length != 1;
      this.multiple2 = !selection.length;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log("this.$refs.tableDate", this.$refs.tableDate);
          this.$refs.tableDate.sort("sort", "ascending");

          if (!this.ids2 || this.ids2.length == 0) {
            this.$message.error("请选择渠道");
            return false;
          }
          const filter_data = this.channelList;
          // const filter_data = this.$refs.tableDate.tableData;
          // console.log("filter_data", filter_data);
          const channels = filter_data
            .filter((item) => {
              return this.ids2.indexOf(item.id) > -1;
            })
            .map((item) => {
              return {
                channel_id: item.id,
                channel_code: item.channel_code,
                channel_name: item.channel_name,
                submit_nums: item.submit_nums,
                sort: item.sort,
              };
            });

          const channels_id = this.ids2;
          addChannelGroup({ ...this.form, channels, channels_id }).then(
            (response) => {
              this.open = false;
              this.$modal.msgSuccess("添加成功");
              this.getList();
            }
          );
        } else {
          console.log(222);
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: undefined,
        sort_type: undefined,
      };
      this.check_ids = [];
      this.$refs.tableDate?.clearSelection();
      this.resetForm("form");
    },
  },
};
</script>
<style lang="postcss" scoped></style>
